#include <event2/event.h>
#include <event2/listener.h>
#include <iostream>
#include <signal.h>
#include <assert.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
using namespace std;

static const char *ip = "192.168.232.128";
static const int port = 12345;

static void sigint_cb(int sockfd, short event_type, void *args) {
    cout << "get Ctrl - C" << endl;
}

static void sigkill_cb(int sockfd, short event_type, void *args) {
    cout << "get Kill" << endl;

    // 添加重启功能，在不添加 persist 选项的情况下
    event *ev = (event*)args;
    if (!evsignal_pending(ev, NULL)) {
        event_del(ev);
        event_add(ev, NULL);
    }
}

int main() {
    event_base *base = event_base_new();

    // 添加 ctrl C 信号事件，处于 no pending
    event *csig = evsignal_new(base, SIGINT, sigint_cb, base);  // 底层是 event_new 的宏
    if (!csig) {
        cerr << "evsignal_new fail" << endl;
        return 1;
    }
    // 添加事件到 pending 状态
    if (event_add(csig, 0)) {
        cerr << "evsignal_add fail" << endl;
        return 1;
    }

    // 通过 event_new 创建 kill 事件，未加 persist 时只生效一次
    event *ekill = event_new(base, SIGTERM, EV_SIGNAL, sigkill_cb, event_self_cbarg()); 
    if (!ekill) {
        cerr << "event_new kill fail" << endl;
        return 1;
    }
    if (event_add(ekill, 0)) {
        cerr << "evsignal_add kill fail" << endl;
        return 1;
    }


    // 进入事件主循环
    event_base_dispatch(base);
    event_free(csig);
    event_base_free(base);
    // 添加 ctrlC 事件后先挂起再杀进程 pkill -9 a.out

}